package com.innovation.chengzhangriji.service;

import android.provider.ContactsContract;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.ChZhRJApplication;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.DiscoverSaveCommentDao;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.DataResponse;
import com.innovation.chengzhangriji.http.DiscoverCommentResponse;
import com.innovation.chengzhangriji.http.DiscoverLikeResponse;
import com.innovation.chengzhangriji.ui.task.ReadImageSizeTask;

import java.lang.reflect.Array;
import java.util.ArrayList;

public abstract class BaseSyncTimelineService extends BaseTimelineService {

    protected final long querySyncTS(int babyID) {
        return DatabaseManager.getInstance(this).querySyncTS(babyID);
    }

    protected final void insertOrReplaceSeverTime(int babyID, long serverTime) {
        DatabaseManager.getInstance(this).insertOrReplaceServerTime(babyID, serverTime);
    }

    protected final void insertOrReplaceLastServerTime(int babyID, String uuid, long serverTime, long lastServerTime, int lastNumber) {
        DatabaseManager.getInstance(this).insertOrReplaceLastServerTime(babyID, uuid, serverTime, lastServerTime, lastNumber);
    }

    protected final void insertOrReplaceInTxTimeline(int babyID, DataResponse data) {
        DatabaseManager.getInstance(this).insertOrReplaceInTxTimelineByServer(babyID, data);
        if(data.getData().length == 0) {
            return;
        }

        // 日记信息
        for (int i = 0; i < data.getData().length; i++) {
            Discover discover = new Discover();
            discover.setDiaryID(data.getData()[i].getUuid());
            discover.setIsDelete(data.getData()[i].getState() == 0);
            if(discover.getIsDelete()) {
                // 删除本地日记
                DatabaseManager.getInstance(this).deleteDiscover(discover.getDiaryID());
            } else {
                discover.setAudio(data.getData()[i].getAudioUrl());
                discover.setVideo(data.getData()[i].getVideoUrl());
                discover.setDuration(data.getData()[i].getLength());
                discover.setGrowthStageID(data.getData()[i].getBabyState());
                discover.setUserID(data.getData()[i].getUserID());
                discover.setMemberName(data.getData()[i].getRole());
                discover.setType(data.getData()[i].getType());
                discover.setMilestone(data.getData()[i].getMilestone());
                discover.setScreenshot(data.getData()[i].getScreenshotUrl());
                discover.setTheme(data.getData()[i].getTheme());
                discover.setText(data.getData()[i].getText());
                discover.setAudio(data.getData()[i].getAudioUrl());
                discover.setBabyID(babyID);
                discover.setDiaryFrom(1); // 来自日记本
                discover.setUserHeadUrl(data.getData()[i].getUserHeadUrl());
                discover.setCreateTS(data.getData()[i].getCreateTS());
                // 更新本地日记
                DatabaseManager.getInstance(this).insertOrReplaceDiscover(discover, data.getData()[i].getPhotoUrls());
                // 评论信息
                ArrayList<DiscoverSaveComment> commentList = new ArrayList<>();
                addComment(data.getData()[i].getCommentList(), commentList, 2, "");
                // 赞信息
                addComment(data.getData()[i].getLikeList(), commentList, 2, "");
                DatabaseManager.getInstance(this).insertOrReplaceDiscoverSaveCommentInTx(commentList);
            }
        }
    }


    // 添加普通评论
    private void addComment(DiscoverCommentResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getCommentState() == 0) {
                // 删除本地评论
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                return;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(1);
            comment.setContent(responses[i].getComment());
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getCommentState());
            comment.setUserID(responses[i].getCommentId());
            comment.setReplyUserID(responses[i].getTargetUserId());
            comment.setReplyNickname(responses[i].getTargetNickname());
            comment.setUserNickname(responses[i].getCommentNickname());
            comment.setReplyIdentity(responses[i].getTargetId());
            comment.setUserHeadUrl(responses[i].getCommentHeadUrl());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getCommentName());
            comment.setReplyMemberName(responses[i].getTargetName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 添加点赞评论
    private void addComment(DiscoverLikeResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getLikeState() == 0) {
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                continue;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(2);
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getLikeState());
            comment.setUserID(responses[i].getLikeId());
            comment.setUserHeadUrl(responses[i].getLikeHeadUrl());
            comment.setUserNickname(responses[i].getLikeNickname());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getLikeName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        ChZhRJApplication.getRefWatcher(this).watch(this);
    }
}
